package com.xiaolei.library.Base;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.xiaolei.library.R;

import java.util.LinkedList;
import java.util.List;

/**
 * 基于Fragment重写的DialogFragment
 */
public abstract class DialogFragment extends BaseFragment
{
    private Config config = new DefaultConfig();
    private final List<Dialog> dialogs = new LinkedList<>();
    private OnShowListener onShowListener;

    public DialogFragment()
    {
        
    }

    public void dismiss()
    {
        for (Dialog dialog : dialogs)
        {
            if (dialog.isShowing())
            {
                dialog.dismiss();
            }
        }
    }

    /**
     * 配置
     *
     * @param config
     */
    public void setConfig(Config config)
    {
        this.config = config;
    }

    /**
     * 设置显示的监听器
     *
     * @param onShowListener
     */
    public void setOnShowListener(OnShowListener onShowListener)
    {
        this.onShowListener = onShowListener;
    }

    @Override
    public void onDestroy()
    {
        this.dismiss();
        super.onDestroy();
    }

    public void onDismiss(DialogInterface dialog)
    {
    }

    public void show(FragmentManager manager)
    {
        if (!this.isAdded())
        {
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.add(this, DialogFragment.class.getName());
            transaction.commitAllowingStateLoss();
            transaction.runOnCommit(() ->
            {
                Dialog dialog = addAndShowDialog();
                if (onShowListener != null)
                {
                    onShowListener.onShow(DialogFragment.this, dialog);
                }
            });
        } else
        {
            Dialog dialog = addAndShowDialog();
            if (onShowListener != null)
            {
                onShowListener.onShow(DialogFragment.this, dialog);
            }
        }
    }
    
    public void show(FragmentManager manager,OnShowListener listener)
    {
        this.setOnShowListener(listener);
        this.show(manager);
    }

    private Dialog addAndShowDialog()
    {
        try
        {
            Context context = requireContext();
            AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.DialogFragment);
            builder.setTitle("");
            builder.setMessage("");
            builder.setOnDismissListener(dialog ->
            {
                DialogFragment.this.onDismiss(dialog);
                dialogs.remove(dialog);
            });
            builder.setCancelable(config.cancelable);
            AlertDialog dialog = builder.create();

            Window window = dialog.getWindow();
            if (window != null)
            {
                int option = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
                window.getDecorView().setSystemUiVisibility(option);
                WindowManager.LayoutParams params = window.getAttributes();
                // 去除四角黑色背景  
                window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                window.setAttributes(params);
            }
            dialog.show();
            View view = getView();
            if (view == null)
                throw new RuntimeException("View没有初始化");
            ViewGroup parent = (ViewGroup) view.getParent();
            if (parent != null)
            {
                parent.removeView(view);
            }
            dialog.setContentView(view);

            window = dialog.getWindow();
            if (window != null)
            {
                window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
                WindowManager.LayoutParams params = window.getAttributes();
                window.setGravity(config.gravity);
                DisplayMetrics dm = new DisplayMetrics();
                window.getWindowManager().getDefaultDisplay().getMetrics(dm);
                window.setWindowAnimations(config.animStyle);
                if (config.width != -1)
                {
                    params.width = config.width;
                }
                if (config.heigh != -1)
                {
                    params.height = config.heigh;
                }
                // 设置周围的暗色系数  
                params.dimAmount = config.dimAmount;
                window.setAttributes(params);
            }
            dialogs.add(dialog);
            return dialog;
        } catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }

    public static interface OnShowListener
    {
        public void onShow(DialogFragment fragment, Dialog dialog);
    }

    /**
     * 配置
     */
    public static class Config
    {
        /**
         * 设置宽度
         */
        public int width = -1;
        /**
         * 设置高度
         */
        public int heigh = -1;
        /**
         * 设置显示的时候，背景的暗色系数
         */
        public float dimAmount = 0.2f;
        /**
         * 设置是否可以点击侧边取消
         */
        public boolean cancelable = true;
        /**
         * 设置位置
         */
        public int gravity = Gravity.CENTER;
        /**
         * 设置动画进出动画
         */
        public int animStyle = R.style.BaseAnimStyle;
    }

    /**
     * 默认的配置
     */
    private static class DefaultConfig extends Config
    {
        private DefaultConfig()
        {
            super.width = ViewGroup.LayoutParams.MATCH_PARENT;
            super.heigh = ViewGroup.LayoutParams.WRAP_CONTENT;
        }
    }
}